import {
	toast,
	clearStorageSync,
	getStorageSync,
	useRouter
} from './utils' // 公共方法
//引入方法
import RequestManager from './requestManager.js'
import store from '@/store/index.js';

console.log(store,store.getters)

const manager = new RequestManager() //创建
const BASE_URL = "https://hetp.hephp.cn/";

let LOPromise = null;

const baseRequest = async (url, method, data = {}, isNeedLogin = true, loading = true) => {
	
	// 如为需要权限的接口 && isLogin 为false
	// 全局promise promise.then拦截其它的请求
	// app.vue 执行resolve / reject
	if(isNeedLogin && !store.getters.isLogin){
		if(!LOPromise) {
			LOPromise = new Promise((res,rej)=>{
				store.state.resolve = res;
				store.state.reject = rej;
			})
		}
		return LOPromise.then(()=>{
			// 生成唯一ID, 如果返回false 代表重复请求
			let requestId = manager.generateId(method, url, data)
			if (!requestId) {
				console.log('重复请求');
				return false
			}
			let header = {
				token: store.getters.token || '',
			}
			
			return new Promise((reslove, reject) => {
				// 开启loading
				loading && uni.showLoading({title: '加载中'})
				uni.request({
					url: BASE_URL + url,
					method: method || 'GET',
					header: header,
					timeout: 10000,
					data: data || {},
					success: (res) => {
						if (res.statusCode == 200) {
							// 业务逻辑，自行修改
							// clearStorageSync()
							// useRouter('/pages/login/login', 'reLaunch')
							reslove(res.data)
						} else {
							toast('网络连接失败，请稍后重试')
							reject(res.data)
						}
					},
					fail: (msg) => {
						toast('网络连接失败，请稍后重试')
						reject(msg)
					},
					complete: () => {
						// 关闭loading
						uni.hideLoading()
						// 请求完成，清除当前请求的唯一ID
						manager.deleteById(requestId)
					},
				})
			})
			
		})

	}else{
		// 生成唯一ID, 如果返回false 代表重复请求
		let requestId = manager.generateId(method, url, data)
		if (!requestId) {
			console.log('重复请求')
			return false
		}
		let header = {
			token: store.getters.token || '',
		}
		
		return new Promise((reslove, reject) => {
			// 开启loading
			loading && uni.showLoading({title: '加载中'})
			uni.request({
				url: BASE_URL + url,
				method: method || 'GET',
				header: header,
				timeout: 10000,
				data: data || {},
				success: (res) => {
					if (res.statusCode == 200) {
						// 业务逻辑，自行修改
						// clearStorageSync()
						// useRouter('/pages/login/login', 'reLaunch')
						reslove(res.data)
					} else {
						toast('网络连接失败，请稍后重试')
						reject(res.data)
					}
				},
				fail: (msg) => {
					toast('网络连接失败，请稍后重试')
					reject(msg)
				},
				complete: () => {
					// 关闭loading
					uni.hideLoading()
					// 请求完成，清除当前请求的唯一ID
					manager.deleteById(requestId)
				},
			})
		})
		
	}
}

const request = {}
const METHODS = ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'];
METHODS.forEach((method) => {
	request[method] = (api, data, isNeedLogin, loading) => baseRequest(api, method, data, isNeedLogin, loading)
})

// 上传图片（单张，多张）
const upLoadFile = async (url,filePath, name, data = {}, loading = true) => {

	let header = {}
	
	return new Promise((reslove, reject) => {
		// 开启loading
		loading && uni.showLoading({title: '加载中'})
		uni.uploadFile({
			url: BASE_URL + url,
			filePath: filePath,
			name: name,
			header: header,
			timeout: 10000,
			formData: data || {},
			success: (res) => {
				let resData = JSON.parse(res.data || {});
				if (res.statusCode == 200) {
					// 业务逻辑，自行修改
					// clearStorageSync()
					// useRouter('/pages/login/login', 'reLaunch')
					reslove(resData)
				} else {
					toast('网络连接失败，请稍后重试')
					reject(resData)
				}
			},
			fail: (msg) => {
				toast('网络连接失败，请稍后重试')
				reject(msg)
			},
			complete: () => {
				// 关闭loading
				uni.hideLoading()
			},
		})
	})
}

request['upLoadFile'] = (api, filePath, name, data, loading) => upLoadFile(api, filePath, name, data, loading);
export default request;